package com.zlsy.es.dianping.service.impl;

import com.zlsy.es.dianping.baseexception.BizException;
import com.zlsy.es.dianping.constan.ErrorStatusEnum;
import com.zlsy.es.dianping.mapper.CategoryMapper;
import com.zlsy.es.dianping.pojo.model.Category;
import com.zlsy.es.dianping.service.CategoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zhouliang
 * @date 2020/3/1 14:56
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    @Override
    public Category create(Category categoryModel) {
        categoryModel.setCreatedAt(new Date());
        categoryModel.setUpdatedAt(new Date());

        try {
            categoryMapper.insertSelective(categoryModel);
        } catch (DuplicateKeyException ex) {
            throw new BizException(ErrorStatusEnum.CATEGORY_NAME_DUPLICATED);
        }

        return get(categoryModel.getId());
    }

    @Override
    public Category get(Integer id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Category> selectAll() {
        return categoryMapper.selectAll();
    }

    @Override
    public Integer countAllCategory() {
        return categoryMapper.countAllCategory();
    }
}
